# !/usr/bin/env python
# -*- coding: UTF-8 -*-
# date: 12/15/11 11:12 AM
# Filename: main.py

#
# Copyright 2011 Youku
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import tornado.web
import tornado.httpserver
import tornado.database
import os
import datetime
import ConfigParser
from util import log
from tornado.options import define, options
from urls import handlers

### parse init arguments from config file ###
config = ConfigParser.RawConfigParser()
config.read('../conf/stat.cfg')

section = 'Mysql'
mysql_host = config.get(section, 'host')
mysql_port = config.getint(section, 'port')
mysql_database = config.get(section, 'database')
mysql_user = config.get(section, 'user')
mysql_password = config.get(section, 'password')

section = 'Tornado'
port = config.getint(section, 'port')
debug = config.getboolean(section, 'debug')
processes = config.getint(section, 'processes')



### define tornado.options value ###
define("mysql_host", default=mysql_host, help="database host")
define("mysql_port", default=mysql_port, help="datebase port", type=int)
define("mysql_database", default=mysql_database, help="database name")
define("mysql_user", default=mysql_user, help="database user")
define("mysql_password", default=mysql_password, help="database password")

define("port", default=port, help="run on the given port", type=int)
define("debug", default=debug, type=bool, help="debug mode or production mode")
define("processes", default=processes, type=int, help="the sub-processes number")


### global variables ###
_log = log.getLogger()
_now = datetime.datetime.now()
_sep = os.linesep

class Application(tornado.web.Application):
    def __init__(self):
        _log.info('class:Application method:__init__()')
        settings = {
            'debug':options.debug,
	}
        tornado.web.Application.__init__(self, handlers, **settings)

        # Have one global connection to the blog DB across all handlers
        try:
            self.db = tornado.database.Connection(
                host=options.mysql_host, database=options.mysql_database,
                user=options.mysql_user, password=options.mysql_password)
        except Exception:
            _log.error('init db error, sys exit!')


def start():
    # parse command line
    #
    # step 1. define default value
    #
    # step 2. parse config file
    #
    # step 3. parse command file
    #
    tornado.options.parse_command_line()

    # start tornado http server
    global http_server
    global ioloop

    http_server = tornado.httpserver.HTTPServer(Application())

    http_server.bind(options.port)
    http_server.start(options.processes)
    tornado.ioloop.IOLoop.instance().start()


def stop():
    global http_server
    global ioloop
    http_server.stop()
    ioloop.stop()


def main():
    start()

if __name__ == "__main__":
    main()


